#include "deepinwiki.h"

#include <QWebEngineView>
#include <httpclient.h>

DeepinWiki::DeepinWiki()
{

}

QString DeepinWiki::name()
{
    return "Deepin Wiki";
}

QString DeepinWiki::prefix()
{
    return "https://wiki.deepin.org/";
}

QList<QListWidgetItem *> DeepinWiki::searching_item(const QString &text)
{
    QList<QListWidgetItem *> list;
    /**
    [
        {
            "operationName": null,
            "variables": {
                "query": "cmake"
            },
            "extensions": {},
            "query": ""
        }
    ]
    */

    QString query =
    "query ($query: String!) {        "
    "    pages {                      "
    "        search(query: $query) {  "
    "            results {            "
    "                id               "
    "                title            "
    "                description      "
    "                path             "
    "                locale           "
    "                __typename       "
    "            }                    "
    "            suggestions          "
    "            totalHits            "
    "            __typename           "
    "        }                        "
    "        __typename               "
    "    }                            "
    "}                                ";

    QVariantMap variables;
    if (text.isEmpty()) {
        variables.insert("query", "Deepin Wiki - 深度百科");
    } else {
        variables.insert("query", text);
    }

    QVariantMap data;
    data.insert("variables", variables);
    data.insert("query", query);

    QVariantList datas;
    datas.append(data);

    Request req("https://wiki.deepin.org/graphql");
    req.setData(datas);

    Response resp = HttpClient::instance().post(req);
    qDebug() << resp.toJson();
    auto results = resp.toList().at(0).toMap().value("data").toMap().value("pages").toMap().value("search").toMap().value("results").toList();
    foreach (auto result, results) {
        auto item = new QListWidgetItem;
        auto var = result.toMap();
        var.value("id");
        var.value("path");
        var.value("locale");

        item->setText(var.value("title").toString());
        item->setData(990,var);

        list << item;
    }

    return list;
}

void DeepinWiki::content_item(const QListWidgetItem *item, QWebEngineView *view)
{
    auto var = item->data(990).toMap();
    auto url = prefix() +  var.value("locale").toString() + "/" +  var.value("path").toString();;
    auto content = HttpClient::instance().get(url).content();


    content = content.mid(content.indexOf("<template"));
    content = content.mid(content.indexOf(">")+1);
    content = content.mid(0, content.indexOf("</template>"));

    view->setHtml(content, prefix());
}
